import {
    createSlice,
    createAsyncThunk
} from "@reduxjs/toolkit";
import { useSelector } from "react-redux";
import { message } from "antd";
import { getInfo, postLogin, postLogout } from "@/api/auth";


const authSlice = createSlice({
    name: "auth",
    initialState: {
        token: localStorage.getItem("token"),
        // 1- 增加存储个人信息的状态
        info: localStorage.info ? JSON.parse(localStorage.info) : {},
        isLoading: false
    },
    reducers: {
        //1.清空Storage 以及state.info,state.token
        clearState(state, { payload }) {
            localStorage.clear();
            state.info = {};
            state.token = payload;
        },
        // 2- 更新个人信息状态
        upInfo(state, { payload }) {
            localStorage.setItem("info", JSON.stringify(payload));
            state.info = payload;
        },
        upToken(state, { payload }) {
            // state.token = localStorage.token = payload;
            state.info = {};
            state.token = payload;
        }
    },
    extraReducers(buildes) {
        buildes.addCase(postLoginAsync2.fulfilled, function useMy(state: any, action: any) {
            // console.log(2222,action);// {type:"aaaa/fulfilled",payload:result}
            message.success(action.payload.message)
            state.isLoading = false;
            state.token = localStorage.token = action.payload.data.token;

        }).addCase(postLoginAsync2.pending, (state, action) => {
            // console.log("pending",action)
            state.isLoading = true;
        })
            .addCase(postLoginAsync2.rejected, (state, action: any) => {
                state.isLoading = false;
            })
    }
})
// 3-声明upToken,upInfo,clearState
const { upToken, upInfo, clearState } = authSlice.actions;
// 1
export const postLoginAsync1 = function (values: any) {
    return async (dispatch: any) => {
        const result = await postLogin(values);
        dispatch(upToken(result.data.token));
        return result;
    }
}
// 2- 扩展
// 2-1: createAsyncThunk是一个函数
// 2-2: 接收两个参数：第一个参数是字符串，第二个参数是一个回调函数
// 2-3:特点：
//    可以通过dispatch接收postLoginAsync2返回的结果： dispatch(postLoginAsync2());
//    可以执行到createAsyncThunk指定的第二个参数（回调函数）
export const postLoginAsync2 = createAsyncThunk("aaaa", async (values: any) => {
    const result = await postLogin(values);
    return result;
});// dispatch(postLoginAsync2(11))

// 4- 获取个人信息
export const getInfoAsync = () => {
    return async (dispatch: any, getState: any) => {
        const state = getState();
        // 判断是否已经获取过个人信息，如果获取过不会再次获取
        if (state.auth.info.name) {
            return;
        }
        const result = await getInfo();
        dispatch(upInfo({
            name: result.data.name,
            avatar: result.data.avatar
        }))
    }
}

// 5. 退出登录
export const postLogoutAsync = () => {
    return async (dispatch: any) => {
        const result = await postLogout();
        dispatch(clearState(null));
    }
}
export const useSelectorAuth = () => useSelector((state: any) => state.auth);
export default authSlice.reducer;


